package com.codeduck.guava.basic;

import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import org.checkerframework.common.returnsreceiver.qual.This;

/**
 * Common object methods: Simplify implementing Object methods, like hashCode() and toString().
 *
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-05-19
 */
public class Demo03 {
    public static void main(String[] args) {

        // 1. equal
        Objects.equal("a", "a"); // returns true
        Objects.equal(null, "a"); // returns false
        Objects.equal("a", null); // returns false
        Objects.equal(null, null); // returns true

        Test test = new Test();

        // 2. hashCode
        Objects.hashCode(test);

        // 3. toString()

        // Returns "Test{key=kk, val=1}"
        MoreObjects.toStringHelper(test)
                .add("key", "kk")
                .add("val", 1)
                .toString();

        //4. compare/compareTo
    }

    static class Test {
        private String key;
        private int val;
    }

    class Person implements Comparable<Person> {
        private String lastName;
        private String firstName;
        private int zipCode;

        // 这段代码很容易混乱，很难查找 bug，而且冗长得让人不舒服。
//        public int compareTo(Person other) {
//            int cmp = lastName.compareTo(other.lastName);
//            if (cmp != 0) {
//                return cmp;
//            }
//            cmp = firstName.compareTo(other.firstName);
//            if (cmp != 0) {
//                return cmp;
//            }
//            return Integer.compare(zipCode, other.zipCode);
//        }

        // 通过ComparisonChain实现
        public int compareTo(Person that) {
            return ComparisonChain.start()
                    .compare(this.firstName, that.firstName)
                    .compare(this.lastName, that.lastName)
//                    .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
                    .result();
        }
    }

}

